#include <stdio.h>
#include <stdlib.h>
#include "funcs.h"
#include <iostream> 
#include <unistd.h>
#include <fcntl.h>

int updateIncarnation(unsigned int i)
{   
    int fd = open("incarnation.txt", O_RDWR); 
    int status = -1; 
    while(status != 0){
        status = lockf(fd, F_LOCK, 0); 
    }
    FILE * incar = NULL; 
    do{
    	incar = fopen("incarnation.txt", "w"); 
    }while(incar == NULL);
    int wait; 
    std::cin >> wait; 
	fprintf(incar, "%i", i);
	fclose(incar);
	lockf(fd, F_ULOCK, 0); 
    return 0;
}

int getIncarnation()
{	
    int fd = open("incarnation.txt", O_RDWR); 
    int status = -1; 
    while(status != 0){
        status = lockf(fd, F_LOCK, 0); 
    }
    FILE * incar = NULL; 
	do{
        incar = fopen("incarnation.txt", "r"); 
    }while(incar == NULL);
	unsigned int i;
	fscanf(incar, "%i", &i);
	fclose(incar);
   	lockf(fd, F_ULOCK, 0); 
    return i;
}

int incrementIncarnation()
{
    int fd = open("incarnation.txt", O_RDWR); 
    int status = -1; 
    while(status != 0){
        status = lockf(fd, F_LOCK, 0); 
    }
    FILE * incar = NULL; 
	do{
        incar = fopen("incarnation.txt", "r+");
    }while(incar == NULL); 
	unsigned int i;
	fscanf(incar, "%i", &i);
	i++;
    FILE * incar2 = NULL;
    do{
        incar2 = fopen("incarnation.txt", "w");
    }while(incar2 == NULL);
 
	fprintf(incar2, "%i", i); 
	fclose(incar);
    fclose(incar2); 	
	lockf(fd, F_ULOCK, 0); 
    return 0;	
}

				
bool randomSuccess(int prob)
{
	//unsigned long limit  = RAND_MAX + 1;
	if(rand()%100 < prob)
		return true; 
	else
		return false; 
}

char randChar()
{
	return (char)(rand()%26 + 97);
}
	
